package com.itheima.api;

import com.itheima.domain.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import javax.annotation.Resource;
import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi{


    @Resource
    private MongoTemplate mongoTemplate;


    /**
     * 保存访客数据
     * @param visitors
     */
    @Override
    public void save(Visitors visitors) {
        Query query = Query.query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate()));
        if (!mongoTemplate.exists(query,Visitors.class)){
            //不存在就保存
            mongoTemplate.save(visitors);
        }
    }

    /**
     * 首页谁看过我
     * @param date
     * @param userId
     * @return
     */
    @Override
    public List<Visitors> visitors(Long date, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        if (date != null){
            //查询在当前用户上一次查看访问列表之后，来访问的用户
            criteria.and("date").gt(date);
        }
        Query query = Query.query(criteria).limit(5).with(Sort.by(Sort.Order.desc("date")));
        return mongoTemplate.find(query,Visitors.class);
    }


}
